package com.lefull.lefullbase.utils.OkGoHelper;

import java.util.ArrayList;

public class HTTPClient {

    protected ArrayList<LifeCycleHandler> lifeCycleHandlers = new ArrayList<>();

    private static HTTPClient instance = null;

    private HTTPClient() {
    }

    public static HTTPClient getInstance() {
        if (instance == null) {
            synchronized (HTTPClient.class) {
                if (instance == null) {
                    instance = new HTTPClient();
                }
            }
        }
        return instance;
    }

    public void sendRequest(final RequestModel requestModel, final ResponseInterface responseInterface) {
        String url = requestModel.baseUrl + requestModel.url;
        LeFullNetCallback callback = new LeFullNetCallback() {
            @Override
            public void leFullNetworkStart() {
                for (LifeCycleHandler handler : lifeCycleHandlers) {
                    handler.willSendRequest(requestModel);
                }
            }

            @Override
            public void leFullNetworkSuccess(String response) {
                ResponseEntity entity = requestModel.parserModel.parserModelResponse(response);
                switch (entity.status) {
                    case 1:
                        responseInterface.onSuccess(entity);
                        break;
                    default:
                        responseInterface.onFailed(entity);
                }
            }

            @Override
            public void leFullNetworkError(int code, String response) {
                String message = HTTPClientConfig.getInstance().getErrorMap().get(code);
                if (message == null) {
                    message = response;
                }
                ResponseEntity entity = new ResponseEntity(code, message, null);
                responseInterface.onFailed(entity);
            }
        };

        switch (requestModel.method) {
            case GET:
                OkGoNetHelper.getRequest(this, requestModel.header, requestModel.parameter, url, requestModel.isCache, callback);
                break;
            case POST:
                OkGoNetHelper.postRequest(this, requestModel.header, requestModel.parameter, url, requestModel.isCache, callback);
                break;
        }
    }
}
